/**
 * 小米风格后台管理系统交互脚本
 */

class XiaomiAdmin {
    constructor() {
        this.currentSection = 'dashboard';
        this.sidebarCollapsed = false;
        this.init();
    }

    /**
     * 初始化管理系统
     */
    init() {
        this.bindEvents();
        this.initSidebar();
        this.loadDashboardData();
        this.startAutoRefresh();
    }

    /**
     * 绑定事件监听器
     */
    bindEvents() {
        // 侧边栏导航
        document.querySelectorAll('.sidebar-nav .nav-link').forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                const section = link.getAttribute('data-section');
                if (section) {
                    this.switchSection(section);
                }
            });
        });

        // 快速操作卡片
        document.querySelectorAll('.quick-action-card').forEach(card => {
            card.addEventListener('click', () => {
                const action = card.getAttribute('data-action');
                this.handleQuickAction(action);
            });
        });

        // 移动端侧边栏切换
        if (window.innerWidth <= 768) {
            this.initMobileSidebar();
        }

        // 窗口大小变化
        window.addEventListener('resize', () => {
            if (window.innerWidth <= 768) {
                this.initMobileSidebar();
            }
        });
    }

    /**
     * 初始化侧边栏
     */
    initSidebar() {
        // 设置默认激活状态
        this.updateSidebarActive('dashboard');
    }

    /**
     * 移动端侧边栏初始化
     */
    initMobileSidebar() {
        // 添加移动端菜单按钮
        if (!document.querySelector('.mobile-menu-btn')) {
            const mobileBtn = document.createElement('button');
            mobileBtn.className = 'btn xiaomi-btn-primary mobile-menu-btn d-md-none';
            mobileBtn.innerHTML = '<i class="fas fa-bars"></i>';
            mobileBtn.style.position = 'fixed';
            mobileBtn.style.top = '70px';
            mobileBtn.style.left = '16px';
            mobileBtn.style.zIndex = '1001';
            
            mobileBtn.addEventListener('click', () => {
                this.toggleMobileSidebar();
            });
            
            document.body.appendChild(mobileBtn);
        }
    }

    /**
     * 切换移动端侧边栏
     */
    toggleMobileSidebar() {
        const sidebar = document.querySelector('.xiaomi-sidebar');
        sidebar.classList.toggle('show');
    }

    /**
     * 切换内容区域
     */
    switchSection(sectionName) {
        // 隐藏所有内容区域
        document.querySelectorAll('.content-section').forEach(section => {
            section.classList.remove('active');
        });

        // 显示目标区域
        const targetSection = document.getElementById(`${sectionName}-section`);
        if (targetSection) {
            targetSection.classList.add('active');
            this.currentSection = sectionName;
        }

        // 更新侧边栏激活状态
        this.updateSidebarActive(sectionName);

        // 执行区域特定的初始化
        this.initSectionContent(sectionName);

        // 移动端自动关闭侧边栏
        if (window.innerWidth <= 768) {
            const sidebar = document.querySelector('.xiaomi-sidebar');
            sidebar.classList.remove('show');
        }
    }

    /**
     * 更新侧边栏激活状态
     */
    updateSidebarActive(sectionName) {
        document.querySelectorAll('.sidebar-nav .nav-link').forEach(link => {
            link.classList.remove('active');
            if (link.getAttribute('data-section') === sectionName) {
                link.classList.add('active');
            }
        });
    }

    /**
     * 初始化区域内容
     */
    initSectionContent(sectionName) {
        switch (sectionName) {
            case 'dashboard':
                this.loadDashboardData();
                break;
            case 'upload':
                this.initUploadSection();
                break;
            case 'mapping':
                this.initMappingSection();
                break;
            case 'conversion':
                this.initConversionSection();
                break;
            case 'download':
                this.initDownloadSection();
                break;
            case 'templates':
                this.initTemplatesSection();
                break;
            case 'history':
                this.initHistorySection();
                break;
        }
    }

    /**
     * 处理快速操作
     */
    handleQuickAction(action) {
        switch (action) {
            case 'upload':
                this.switchSection('upload');
                break;
            case 'templates':
                this.switchSection('templates');
                break;
            case 'history':
                this.switchSection('history');
                break;
            default:
                console.log('未定义的快速操作:', action);
        }
    }

    /**
     * 加载仪表板数据
     */
    loadDashboardData() {
        // 模拟数据加载
        this.animateCounters();
        this.loadRecentActivity();
        this.initChart();
    }

    /**
     * 数字动画效果
     */
    animateCounters() {
        const counters = [
            { element: '.xiaomi-stat-card.orange .stat-number', target: 1247 },
            { element: '.xiaomi-stat-card.blue .stat-number', target: 892 },
            { element: '.xiaomi-stat-card.green .stat-number', target: 98.5 },
            { element: '.xiaomi-stat-card.red .stat-number', target: 13 }
        ];

        counters.forEach(counter => {
            const element = document.querySelector(counter.element);
            if (element) {
                this.animateNumber(element, 0, counter.target, 2000);
            }
        });
    }

    /**
     * 数字动画
     */
    animateNumber(element, start, end, duration) {
        const startTime = performance.now();
        const isFloat = end % 1 !== 0;

        const animate = (currentTime) => {
            const elapsed = currentTime - startTime;
            const progress = Math.min(elapsed / duration, 1);
            
            const easeOutCubic = 1 - Math.pow(1 - progress, 3);
            const current = start + (end - start) * easeOutCubic;
            
            if (isFloat) {
                element.textContent = current.toFixed(1) + '%';
            } else {
                element.textContent = Math.floor(current).toLocaleString();
            }

            if (progress < 1) {
                requestAnimationFrame(animate);
            }
        };

        requestAnimationFrame(animate);
    }

    /**
     * 加载最近活动
     */
    loadRecentActivity() {
        // 模拟活动数据更新
        const activities = document.querySelectorAll('.activity-item');
        activities.forEach((activity, index) => {
            setTimeout(() => {
                activity.style.opacity = '0';
                activity.style.transform = 'translateX(-20px)';
                
                setTimeout(() => {
                    activity.style.transition = 'all 0.3s ease';
                    activity.style.opacity = '1';
                    activity.style.transform = 'translateX(0)';
                }, 100);
            }, index * 200);
        });
    }

    /**
     * 初始化图表
     */
    initChart() {
        const canvas = document.getElementById('conversionChart');
        if (!canvas) return;

        const ctx = canvas.getContext('2d');
        
        // 简单的图表绘制
        ctx.fillStyle = '#f5f5f5';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        // 绘制折线图
        ctx.strokeStyle = '#ff6900';
        ctx.lineWidth = 3;
        ctx.beginPath();
        
        const data = [20, 45, 30, 60, 35, 70, 55, 80];
        const stepX = canvas.width / (data.length - 1);
        const maxValue = Math.max(...data);
        
        data.forEach((value, index) => {
            const x = index * stepX;
            const y = canvas.height - (value / maxValue) * (canvas.height - 40) - 20;
            
            if (index === 0) {
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
            }
        });
        
        ctx.stroke();
        
        // 绘制数据点
        ctx.fillStyle = '#ff6900';
        data.forEach((value, index) => {
            const x = index * stepX;
            const y = canvas.height - (value / maxValue) * (canvas.height - 40) - 20;
            
            ctx.beginPath();
            ctx.arc(x, y, 4, 0, Math.PI * 2);
            ctx.fill();
        });
        
        // 添加标题
        ctx.fillStyle = '#666';
        ctx.font = '14px sans-serif';
        ctx.textAlign = 'center';
        ctx.fillText('数据转换趋势 (最近7天)', canvas.width / 2, 20);
    }

    /**
     * 初始化上传区域
     */
    initUploadSection() {
        console.log('初始化上传区域');
        // 这里可以添加上传相关的初始化逻辑
    }

    /**
     * 初始化映射区域
     */
    initMappingSection() {
        console.log('初始化映射区域');
        // 这里可以添加映射相关的初始化逻辑
    }

    /**
     * 初始化转换区域
     */
    initConversionSection() {
        console.log('初始化转换区域');
        // 这里可以添加转换相关的初始化逻辑
    }

    /**
     * 初始化下载区域
     */
    initDownloadSection() {
        console.log('初始化下载区域');
        // 这里可以添加下载相关的初始化逻辑
    }

    /**
     * 初始化模板区域
     */
    initTemplatesSection() {
        console.log('初始化模板区域');
        // 这里可以添加模板相关的初始化逻辑
    }

    /**
     * 初始化历史区域
     */
    initHistorySection() {
        console.log('初始化历史区域');
        // 这里可以添加历史记录相关的初始化逻辑
    }

    /**
     * 开始自动刷新
     */
    startAutoRefresh() {
        // 每30秒刷新一次统计数据
        setInterval(() => {
            if (this.currentSection === 'dashboard') {
                this.refreshDashboardStats();
            }
        }, 30000);
    }

    /**
     * 刷新仪表板统计数据
     */
    refreshDashboardStats() {
        // 模拟数据更新
        const stats = document.querySelectorAll('.xiaomi-stat-card');
        stats.forEach(stat => {
            stat.style.transform = 'scale(0.95)';
            setTimeout(() => {
                stat.style.transform = 'scale(1)';
            }, 150);
        });
    }

    /**
     * 显示通知
     */
    showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `alert alert-${type} xiaomi-notification`;
        notification.style.position = 'fixed';
        notification.style.top = '80px';
        notification.style.right = '20px';
        notification.style.zIndex = '9999';
        notification.style.minWidth = '300px';
        notification.style.boxShadow = 'var(--xiaomi-shadow-hover)';
        notification.innerHTML = `
            <div class="d-flex align-items-center">
                <i class="fas fa-info-circle me-2"></i>
                <span>${message}</span>
                <button type="button" class="btn-close ms-auto" onclick="this.parentElement.parentElement.remove()"></button>
            </div>
        `;

        document.body.appendChild(notification);

        // 3秒后自动移除
        setTimeout(() => {
            if (notification.parentElement) {
                notification.remove();
            }
        }, 3000);
    }

    /**
     * 显示加载状态
     */
    showLoading(container, message = '加载中...') {
        const loadingHtml = `
            <div class="xiaomi-loading-container text-center py-5">
                <div class="xiaomi-loading mb-3"></div>
                <p class="text-muted">${message}</p>
            </div>
        `;

        if (typeof container === 'string') {
            const element = document.querySelector(container);
            if (element) {
                element.innerHTML = loadingHtml;
            }
        } else {
            container.innerHTML = loadingHtml;
        }
    }

    /**
     * 隐藏加载状态
     */
    hideLoading(container) {
        const loadingContainer = container.querySelector('.xiaomi-loading-container');
        if (loadingContainer) {
            loadingContainer.remove();
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    window.xiaomiAdmin = new XiaomiAdmin();
});

// 全局工具函数
window.XiaomiUtils = {
    /**
     * 格式化文件大小
     */
    formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },

    /**
     * 格式化时间
     */
    formatTime(date) {
        const now = new Date();
        const diff = now - date;
        const minutes = Math.floor(diff / 60000);
        
        if (minutes < 1) return '刚刚';
        if (minutes < 60) return `${minutes}分钟前`;
        
        const hours = Math.floor(minutes / 60);
        if (hours < 24) return `${hours}小时前`;
        
        const days = Math.floor(hours / 24);
        return `${days}天前`;
    },

    /**
     * 生成唯一ID
     */
    generateId() {
        return 'xiaomi_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    },

    /**
     * 防抖函数
     */
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },

    /**
     * 节流函数
     */
    throttle(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }
};